import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/view/Login/index.vue'),
      children: [
        {
          path: '/login',
          component: () => import('@/view/Login/components/password.vue')
        },
        {
          path: '/code',
          component: () => import('@/view/Login/components/code.vue')
        },
        {
          path: '/register',
          component: () => import('@/view/Login/components/register.vue')
        }
      ]
    },
    {
      path: '/',
      component: () => import('@/view/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/view/Home/index.vue')
        },
        {
          path: '/dynamic',
          component: () => import('@/view/Dynamic/index.vue')
        },
        {
          path: '/my',
          component: () => import('@/view/My/index.vue'),
          redirect: '/my/dynamic',
          children: [
            {
              path: '/my/dynamic',
              component: () => import('@/view/My/components/MyDynamic.vue')
            },
            {
              path: '/my/star',
              component: () => import('@/view/My/components/MyStar.vue')
            },
            {
              path: '/my/collect',
              component: () => import('@/view/My/components/MyCollect.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/search',
      component: () => import('@/view/Search/index.vue')
    },
    {
      path: '/scenic-detail/:id',
      component: () => import('@/view/ScenicDetail/index.vue')
    },
    {
      path: '/gpt',
      component: () => import('@/view/Gpt/index.vue')
    },
    {
      path: '/settings',
      component: () => import('@/view/Settings/index.vue')
    },
    {
      path: '/publish',
      component: () => import('@/view/Publish/index.vue')
    },
    {
      path: '/dynamic-detail/:id',
      component: () => import('@/view/DynamicDetail/index.vue')
    }
  ]
})

// 访问权限控制
router.beforeEach(to => {
  const wihteList = [
    '/login',
    '/code',
    '/register',
    '/home',
    '/search',
    '/dynamic'
  ]
  const token = localStorage.getItem('token')

  // 如果没有token并且不在白名单中，跳转到登录页
  if (!token && !wihteList.some(route => to.path.startsWith(route)))
    return '/login?returnUrl=' + to.path
  // 如果已经登录了，访问登录页，跳转到首页
  if (token && to.path === '/login') return '/home'
})

export default router
